package com.wf.controller;

import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.wf.domain.SysUser;
import com.wf.dto.LoginDTO;
import com.wf.dto.PageDTO;
import com.wf.dto.UserPageDTO;
import com.wf.properties.WxMpProperties;
import com.wf.propertity.JwtProperties;
import com.wf.service.SysRoleService;
import com.wf.service.SysUserService;
import com.wf.utils.RedisUtil;
import com.wf.vo.AdminVO;
import com.wf.web.base.BaseController;
import com.wf.web.domain.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户接口
 * 负责处理与用户相关的HTTP请求，包括登录、注册、信息查询等
 *
 * @author mpk
 * @since 2024/10/2 10:09:38
 */
@RestController
@CrossOrigin
@RequestMapping("/user")
@Slf4j
public class UserController extends BaseController {

    @Resource
    SysUserService userService;

    @Autowired
    JwtProperties jwtProperties;

    @Autowired
    SysUserService sysUserService;

    @Autowired
    SysRoleService roleService;

    @Autowired
    RedisUtil redisUtil;

    /**
     * 用户登录接口
     *
     * @param loginDTO 包含用户登录信息的数据传输对象
     * @return 登录结果，包含用户信息和令牌
     */
    @PostMapping("login")
    public Result login(@RequestBody LoginDTO loginDTO) {
        Map<String, Object> res = userService.login(loginDTO);
        return Result.success(res);
    }

    /**
     * QQ登录接口
     *
     * @param loginDTO 包含用户QQ登录信息的数据传输对象
     * @return 登录结果，包含用户信息和令牌
     */
    @PostMapping("loginByQQ")
    public Result loginByQQ(@RequestBody LoginDTO loginDTO) {
        Map<String, Object> res = userService.login(loginDTO);
        return Result.success(res);
    }

    /**
     * 微信登录回调接口
     *
     * @param request HTTP请求对象，包含微信返回的code和state参数
     * @return 微信登录结果
     */
    @GetMapping("wxReturn")
    public Result wechatReturn(HttpServletRequest request) {
        String code = request.getParameter("code");
        String state = request.getParameter("state");
        HashMap<String, Object> map = new HashMap<>();
        map.put("appid", WxMpProperties.appId);
        map.put("secret", WxMpProperties.secret);
        map.put("code", code);
        map.put("state", state);
        map.put("grant_type", "authorization_code");
        String response = HttpUtil.get("https://api.weixin.qq.com/sns/oauth2/access_token", map);
        JSONObject jsonObject = JSONUtil.parseObj(response);
        String accessToken = jsonObject.getStr("access_token");
        String openid = jsonObject.getStr("openid");
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("access_token", accessToken);
        hashMap.put("openid", openid);
        hashMap.put("lang", "zh_CN");
        String userInfo = HttpUtil.get("https://api.weixin.qq.com/sns/userinfo", hashMap);
        log.info(userInfo);
        JSONObject parseObj = JSONUtil.parseObj(userInfo);
        String nickname = parseObj.getStr("nickname");
        String headimgurl = parseObj.getStr("headimgurl");
        Integer sex = parseObj.getInt("sex");
        log.info("用户昵称:{}", nickname);
        log.info("openid:{}", openid);
        log.info("用户头像:{}", headimgurl);
        log.info("用户性别:{}", sex);
        return success();
    }

    /**
     * 微信登录接口，生成微信登录二维码
     *
     * @param response HTTP响应对象，用于返回二维码图片
     * @throws IOException 生成二维码过程中可能出现的异常
     */
    @GetMapping("loginByWechat")
    public void loginByWechat(HttpServletResponse response) throws IOException {
        String encode = URLEncoder.encode("http://2ffb83e6.r29.cpolar.top/user/wxReturn", "UTF-8");
        String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxa09ed53f3440b8df&redirect_uri=" + encode + "&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect&forcePopup=true";
        response.setContentType("image/png");
        QrCodeUtil.generate(url, 300, 300, "jpg", response.getOutputStream());
    }

    /**
     * 获取当前登录用户信息
     *
     * @return 当前登录用户的信息
     */
    @GetMapping("userInfo")
    public Result getUserInfo() {
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (principal instanceof SysUser) {
            SysUser user = (SysUser) principal;
            return this.success(user);
        } else {
            return this.failure("用户信息获取失败");
        }
    }

    /**
     * 用户登出
     *
     * @return 登出结果信息
     */
    @GetMapping("logout")
    public Result logout() {
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (principal instanceof SysUser) {
            SysUser user = (SysUser) principal;
            user.getUserId();
            redisUtil.del("login:" + user.getUserId());
        }
        return success("退出登录");
    }

    /**
     * 获取管理员列表
     *
     * @param pageDTO 分页查询参数
     * @return 管理员列表
     */
    @PostMapping("adminList")
    public Result adminList(@RequestBody PageDTO pageDTO) {
        List<AdminVO> adminList = sysUserService.getAdminList(pageDTO);
        return success(adminList);
    }

    /**
     * 获取用户列表
     *
     * @param userPageDTO 用户分页查询参数
     * @return 用户列表
     */
    @PostMapping("userList")
    public Result userList(@RequestBody UserPageDTO userPageDTO) {
        List<SysUser> users = userService.getUserList(userPageDTO);
        return success(users);
    }

    /**
     * 更新用户信息
     *
     * @param user 待更新的用户信息
     * @return 更新结果
     */
    @PostMapping("updateUser")
    public Result updateUser(  ) {
//        boolean b = sysUserService.updateById(user);
//        if (!b) {
//            return failure("更新失败");
//        }
        System.out.println("AAAA");
        return success();
    }

    /**
     * 删除用户
     *
     * @param user 待删除的用户信息
     * @return 删除结果
     */
    @PostMapping("deleteUser")
    public Result deleteUser(@RequestBody SysUser user) {
        boolean b = sysUserService.removeById(user.getUserId());
        if (!b) {
            return failure("删除失败");
        }
        return success();
    }

    /**
     * 获取用户角色列表
     *
     * @param user 待查询的用户信息
     * @return 用户角色列表
     */
    @PostMapping("getRoleList")
    public Result getRoleList(@RequestBody SysUser user) {
        boolean b = sysUserService.removeById(user.getUserId());
        if (!b) {
            return failure("删除失败");
        }
        return success();
    }
}
